/**
* @author Meng Zhang
**/
#include "stdafx.h"
#include "Accelerator.h"
#include "../tinyurl/tinyxml.h"
#include "../mfc/resource.h"

#pragma warning(disable: 4996)

namespace {
	TiXmlNode *root;
	Accelerator *accel;
    
	int ParseModifier(char* buf) {
		int ret = 0;
		int len  = strlen(buf);
		for (int i = 0;i<len;++i) {
			if (buf[i]=='-') {
				switch(buf[i-1]) {
					case 'C':
						ret|=MOD_CONTROL;
						break;
					case 'M':
						ret|=MOD_ALT;
						break;
					case 'S':
						ret|=MOD_SHIFT;
						break;
					default:
						break;
				}
			}
		}
		return ret;
	}

	int ParseKey(char* buf) {
		return toupper(buf[strlen(buf)-1]);
	}

	int ParseStr(const std::string & str, int *modifier, int *key) {
		int step = 0,pos = 0;
		char buf[100];
		while (sscanf(str.c_str()+pos,"%[^,],",buf)!=EOF) {
			int m = ParseModifier(buf);
			int k = ParseKey(buf);
			modifier[step] = m;
			key[step] = k;
			++step;
			pos+=strlen(buf)+1;
			if (pos>=(int)str.length())
				break;
		}
		return step;
	}
	
	BOOL AssignStr(const char* name , UINT cmd) {
		TiXmlNode* node = root->FirstChild(name);
		int modifier[__MAX_ACCELERATOR_STEP];
		int key[__MAX_ACCELERATOR_STEP];
		int step = ParseStr(node->FirstChild()->Value(),modifier,key);
		return accel->RegisterKey(cmd,modifier,key,step);
	}
}

BOOL LoadAccelConfig(char* filepath,Accelerator *_accel , StringToCmd strCmd[] ) {
	TiXmlDocument doc(filepath);
	doc.LoadFile();
	root = doc.FirstChild("keyboard");
	if (!root)
		return FALSE;
	accel = _accel;
	for (int i = 0;strCmd[i].sName!=0;++i) {
		if (!AssignStr(strCmd[i].sName,strCmd[i].uCmd))
			return FALSE;
	}
	return TRUE;
// 	AssignStr("open",ID_FILE_NEW_OPEN);
// 	AssignStr("save",ID_FILE_SAVE);
// 	AssignStr("close",ID_FILE_CLOSE);
// 	AssignStr("exit",ID_APP_EXIT);
// 
// 	AssignStr("cut",ID_EDIT_CUT);
// 	AssignStr("copy",ID_EDIT_COPY);
// 	AssignStr("paste",ID_EDIT_PASTE);
// 	AssignStr("undo",ID_EDIT_UNDO);
// 	AssignStr("redo",ID_EDIT_REDO);
// 
// 	AssignStr("maxize",ID_WINDOW_MAXIMA);
// 	AssignStr("split_vertical",ID_WINDOW_SPLIT);
// 	AssignStr("split_horizontal",ID_WINDOW_SPLIT_VERTICAL);
// 	AssignStr("about",ID_APP_ABOUT);
}

BOOL LoadAccelConfig( char* filepath, Accelerator* _accel, char* str , UINT cmd ) {
	TiXmlDocument doc(filepath);
	doc.LoadFile();
	root = doc.FirstChild("keyboard");
	if (!root)
		return FALSE;

	accel = _accel;
	if (!AssignStr(str,cmd))
		return FALSE;
	return TRUE;
}